import React, { useEffect, useRef, useState, useLayoutEffect } from 'react';
import {
    View,
    TextInput,
    Text,
    TouchableOpacity,
    StyleSheet,
    Modal,
    KeyboardAvoidingView,
    Platform,
    Image,
    Keyboard,
    Alert

} from 'react-native';
import { useSelector, useDispatch } from 'react-redux';
import { loadPosts } from '@/store/postSlice';
import store from "@/store/postindex";
import { addComment } from '@/store/postSlice';
import EmojiSelector, { Categories } from 'react-native-emoji-selector'; // Emoji 选择器库
import { router } from 'expo-router';
// import posts from "@/mock/posts";
import Mock from 'mockjs';


const CommentModal = ({ postId, visible, onClose, route }) => {
    const posts = useSelector((state) => state.post.posts);

    // const { id } = route.params || '1';
    const id = '6'
    const dispatch = useDispatch();
    useEffect(() => {
        store.dispatch(loadPosts()); // 加载存储的帖子
    }, [dispatch])
    // const post = posts.find(p => p.id === id);
    const post = useSelector((state) =>
        state.post.posts.find((p) => p.id === id)
    );
    // console.log(post,'post');
    

    const [comment, setComment] = useState(''); // 用户输入的评论
    const [showEmojiPicker, setShowEmojiPicker] = useState(false); // 控制 emoji 选择器显示

    const textInputRef = useRef<TextInput>(null); // 引用 TextInput
    const [isToggling, setIsToggling] = useState(false);
    // 在Modal打开后设置焦点
    useLayoutEffect(() => {
        if (visible) {
            setTimeout(() => {
                textInputRef.current?.focus(); // 确保焦点设置成功
            }, 300); // 延迟以避免动画冲突
        }
    }, [visible]);
    // 添加评论的逻辑
    const handleAddComment = () => {
        const newComment = {
            id: Mock.mock('@guid'),
            content: comment, // 评论内容
            createTime: new Date().toISOString(), // 当前时间
            user: {
                id: id, // 示例用户 ID（需要从登录状态中获取）
                name: post.name, // 示例用户名
                avatar: post.avatar, // 示例头像
            },
        }
        dispatch(addComment({ postid: postId, comment: newComment }));
        console.log(newComment, 'new');

        setComment(''); // 清空输入框
        Keyboard.dismiss()
        onClose()
        // setTimeout(() => {
        //     onClose(); // 延迟关闭
        // }, 300); // 给评论提交留出时间

    };
    return (
        <Modal visible={visible} animationType="slide" transparent>
            <KeyboardAvoidingView
                style={styles.modalContainer}
                behavior={Platform.OS === 'ios' ? 'padding' : undefined} // iOS 弹性调整
                keyboardVerticalOffset={showEmojiPicker ? 0 : 60} // 动态调整
            >
                {/* 关闭 */}
                <TouchableOpacity onPress={onClose}>
                    <View style={styles.top}></View>
                </TouchableOpacity>
                <View style={styles.modalContent}>
                    {/* 输入框 */}
                    <TextInput
                        ref={textInputRef} // 引用 TextInput
                        style={styles.textInput}
                        value={comment}
                        onChangeText={setComment}
                        placeholder="输入评论..."
                        multiline
                        // onFocus={() => setShowEmojiPicker(false)} // 输入框聚焦时隐藏 Emoji Picker
                        // autoFocus // 自动聚焦，弹出键盘
                        onFocus={() => Keyboard.isVisible()}
                    />

                    {/* 操作按钮 */}
                    <View style={styles.actions}>
                        <TouchableOpacity
                            style={styles.emojiButton}
                            onPress={() => {
                                if (isToggling) return; // 防止重复点击
                                setIsToggling(true);
                                Keyboard.dismiss();
                                setShowEmojiPicker((prev) => !prev);
                                setTimeout(() => setIsToggling(false), 300); // 解锁点击
                            }}
                        >
                            <Image source={require('../../assets/images/emoji.png')} style={styles.emoji} />
                        </TouchableOpacity>
                        <TouchableOpacity onPress={handleAddComment}>
                            <Image source={require('../../assets/images/send.png')} style={styles.emoji} />
                        </TouchableOpacity>
                    </View>
                </View>
                {/* Emoji 选择器 */}
                {/* {showEmojiPicker && (
                    <EmojiSelector
                        onEmojiSelected={(emoji) => setComment((prev) => prev + emoji)}
                        category={Categories.SMILEYS}
                        showSearchBar={false}
                        showHistory={true}
                        style={styles.emojiPicker}
                    />
                )} */}
                {/* Emoji 选择器 */}
                {showEmojiPicker && (
                    <View style={styles.emojiPickerContainer}>
                        <EmojiSelector
                            onEmojiSelected={(emoji) => setComment((prev) => prev + emoji)}
                            category={Categories.emotion}
                            showSearchBar={false}
                            showHistory={true}
                        />
                    </View>
                )}
                {/* 关闭按钮 */}
                {/* <TouchableOpacity style={styles.closeButton} onPress={onClose}>
                    <Text style={styles.closeButtonText}>关闭</Text>
                </TouchableOpacity> */}
            </KeyboardAvoidingView>
        </Modal>
    );
};

export default CommentModal;

const styles = StyleSheet.create({
    modalContainer: {
        flex: 1,
        // backgroundColor: 'rgba(0, 0, 0, 0.5)',
        justifyContent: 'flex-end',
        width: '100%',
        height: '100%'
    },
    top: {
        width: '100%',
        height: 100
    },
    modalContent: {
        flexDirection: 'row',
        backgroundColor: 'white',
        borderTopLeftRadius: 10,
        borderTopRightRadius: 10,
        padding: 16,
        width: '100%'
    },
    textInput: {
        height: 40,
        width: '80%',
        borderColor: '#ddd',
        borderWidth: 1,
        borderRadius: 8,
        padding: 8,
        fontSize: 16,
        marginBottom: 16,
    },
    emoji: {
        width: 30,
        height: 30,
        marginTop: -15,
        marginLeft: -2
    },
    actions: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
    },
    emojiButton: {
        padding: 10,
    },
    emojiButtonText: {
        fontSize: 24,
    },
    sendButton: {
        backgroundColor: '#007bff',
        paddingVertical: 10,
        paddingHorizontal: 20,
        borderRadius: 8,
    },
    sendButtonText: {
        color: 'white',
        fontSize: 16,
    },

    emojiPicker: {
        height: 250,
    },
    closeButton: {
        alignItems: 'center',
        paddingVertical: 10,
        backgroundColor: '#f0f0f0',
    },
    closeButtonText: {
        fontSize: 16,
        color: '#333',
    },
    emojiPickerContainer: {
        backgroundColor: 'white',
        borderTopLeftRadius: 10,
        borderTopRightRadius: 10,
        overflow: 'hidden',
        height: 250, // 控制 Emoji Selector 高度
    },

});